package com.net;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by peak on 2016/1/11.
 */
public class DownloadTest {
    public static void main(String[] args) throws Exception{
            URL url = new URL("http://pc.duowan.com/uploads/allimg/2010-02/261F338-6-334122.jpg");
        URLConnection conn = url.openConnection();

        InputStream in = conn.getInputStream();
        int index = url.getFile().lastIndexOf("/");
        String fileName = url.getFile().substring(index+1);

        FileOutputStream out = new FileOutputStream(fileName);

        String contentType = conn.getContentType();
        int contentLength = conn.getContentLength();
        byte[] buff = new byte[contentLength];
        int d=-1;
        int s=0;
        while ((d=in.read(buff,s,contentLength-s))!=-1){
            s+=d;
            if(s>=contentLength){
                break;
            }
        }
        out.write(buff);

        in.close();
        out.close();
    }
}
